package ca.cbc.msb.mq;

import ca.cbc.medialib.util.ApplicationContextUtil;
import ca.cbc.msb.entity.MSBMessage;
import ca.cbc.msb.persistence.ProcessingStatusPersistence;
import ca.cbc.msb.util.ProgressReport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.JMSException;
import javax.naming.NamingException;

/**
 * This class listens to dead-letter-queue for the Change notification messages. If a change notification is received while processing
 * the same release, MSB rolls back the release, waiting for the previous ones to finish processing. In case the previous notification
 * did not finish on time, this messages come to this handler
 * @author : Arash Bizhanzadeh <arash.bizhanzadeh@cbc.ca>
 *         Date: 11-09-26
 *         Time: 10:26 AM
 *         CBC.ca All rights reserved.
 */
public class GeneralNotificationFailedMessageHandler implements MessageHandler{
    private static Logger logger = LoggerFactory.getLogger(GeneralNotificationFailedMessageHandler.class);
    private ProcessingStatusPersistence processingStatusPersistence;

    public GeneralNotificationFailedMessageHandler() throws NamingException, JMSException {
    	processingStatusPersistence = ApplicationContextUtil.instance.getApplicationContext().getBean(ProcessingStatusPersistence.class);  	          
    }
    
    @Override
    public void handle(MSBMessage message, MessageUtil messageUtil) throws NamingException, JMSException {
    	messageUtil.commit();
        processingStatusPersistence.removeProcessingFlag(message);
        logger.error("***Notification timed out for message {}", message);
        ProgressReport.instance.report("Timed out while waiting for the previous changes to finish. Not Processed. Finished " + message);   
    }
}
